<template>
    <el-dialog title="选择课程" :close-on-click-modal="false" v-model="visible" :width="1000" append-to-body @closed="close">
        <div :style="`height: ${height}px; border: 1px solid #e6e6e6;`">
            <el-container>
                <el-container class="is-vertical">
                    <div class="panel-search-box">
                        <div class="panel-search">
                            <el-input v-model="search.courseName" style="width: 150px;" placeholder="课程名称" clearable></el-input>
                            <el-select v-model="search.categoryId" placeholder="类型" clearable filterable class="w165">
						        <el-option :label="item.name" :value="item.id" v-for="(item,index) in categoryData" :key="index"></el-option>
					        </el-select>
                            <el-select v-model="search.levelId" placeholder="学段" clearable filterable class="w165">
						        <el-option :label="item.name" :value="item.id" v-for="(item,index) in levelData" :key="index"></el-option>
					        </el-select>
                            <el-select v-model="search.difficultyId" placeholder="难度" clearable filterable class="w165">
                                <el-option :label="item.name" :value="item.id" v-for="(item,index) in difficultyData" :key="index"></el-option>
                            </el-select>
                            <el-select v-model="search.bookId" placeholder="教材" clearable filterable class="w165">
                                <el-option :label="item.name" :value="item.id" v-for="(item,index) in bookData" :key="index"></el-option>
                            </el-select>
                            <el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
                        </div>
                    </div>
                    <el-main class="nopadding">
                        <scTable ref="table_member_all" :apiObj="$API.user.course.list" :params="defaultSearch" @dataChange="changedData" remoteSort @select="selectionRow" @select-all="selectionAll">
                            <el-table-column type="selection" width="50"></el-table-column>
                            <el-table-column label="课程" prop="name">
                                <template #default="scope">
                                    {{ scope.row.course ? scope.row.course.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="类型" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.category ? scope.row.course.category.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="学段" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.level ? scope.row.course.level.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="难度" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.difficulty ? scope.row.course.difficulty.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="教材" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.book ? scope.row.course.book.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="总词数" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course ? scope.row.course.words : '0' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="已学" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.knowWords || 0 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="状态" prop="status" width="100" align="center">
                                <template #default="scope">
                                    <el-tag size="mini" type="success" v-if="scope.row.status.value == 1">{{scope.row.status.name}}</el-tag>
                                    <el-tag size="mini" type="info" v-else>{{scope.row.status.name}}</el-tag>
                                </template>
                            </el-table-column>
                        </scTable>
                    </el-main>
                </el-container>
            </el-container>
        </div>
        <el-dialog :title="`已选择课程`" :close-on-click-modal="false" v-model="selected_visible" :width="1000" append-to-body @closed="selected_visible = false">
            <div style="height: 450px;">
                <el-button type="danger" style="margin-bottom: 20px;" plain icon="el-icon-delete" :disabled="selectedMembers.length==0" @click="deleteSelectedMembers">移除</el-button>
                <el-container class="is-vertical">
                    <el-main class="nopadding">
                        <scTable ref="table_selected" :hidePagination="true" remoteSort :data="temporary_selected" @selection-change="selectionMembers">
                            <el-table-column type="selection" width="50"></el-table-column>
                            <el-table-column label="课程" prop="name">
                                <template #default="scope">
                                    {{ scope.row.course ? scope.row.course.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="类型" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.category ? scope.row.course.category.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="学段" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.level ? scope.row.course.level.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="难度" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.difficulty ? scope.row.course.difficulty.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="教材" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course && scope.row.course.book ? scope.row.course.book.name : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="总词数" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.course ? scope.row.course.words : '0' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="已学" align="center" width="120">
                                <template #default="scope">
                                    {{ scope.row.knowWords || 0 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="状态" prop="status" width="100" align="center">
                                <template #default="scope">
                                    <el-tag size="mini" type="success" v-if="scope.row.status.value == 1">{{scope.row.status.name}}</el-tag>
                                    <el-tag size="mini" type="info" v-else>{{scope.row.status.name}}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" align="right" width="140">
                                <template #default="scope">
                                    <el-button type="text" size="small" @click="table_delete(scope.row, scope.$index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </scTable>
                    </el-main>
                </el-container>
            </div>
            <template #footer>
                <el-button @click="selected_visible = false">关闭</el-button>
                <el-button @click="handleChange" type="primary">确定 <span v-if="temporary_selected.length">({{temporary_selected.length}})</span> </el-button>
            </template>
        </el-dialog>
        <template #footer>
            <el-button @click="close">关闭</el-button>
            <el-button type="primary" v-if="selected.length>0" @click="openSelection">查看已选{{selected.length}}个</el-button>
            <el-button type="primary" @click="submitAdd">确定</el-button>
        </template>
    </el-dialog>
</template>

<script>
import { unique } from '@/utils'
import scFrame from '@/components/scFrame'
export default {
    props: {
        height: { type: String, default: '500' },
        isitem: { type: Boolean, default: false },
        isposition: { type: Boolean, default: false },
        islevel: { type: Boolean, default: false },
        apiTreeObj: {type: Object, default: () => {}},
        treeSearch: {type: Object, default: () => {}},
        merberSearch: {type: Object, default: () => {}},
        defaultSearch: {type: Object, default: () => {}},
        userId: {type: Number, default: 0},
    },
    components: {
        scFrame
    },
    data() {
        return {
            // 所有员工筛选
            search: {
                name: null,
                status: 1,
                userId: null
            },
            visible: false,
            //已选择成员列表
            selected: [],
            selectedObject: [],
            //角色列表
            rolelist: [],
            //左侧树
            tree: [],
            // 职位列表
            position_list: [],
            // 职级列表
            level_list: [],
            //已选择的树项
            selectedTree: [],
            //已选择用户弹框
            selected_visible: false,
            //已选择的已选择成员列表
            selectedMembers: [],
            //临时de已选择的成员列表(用于确认的时候判断是否与“已选择的成员列表”相同，不同则代表有删除)
            temporary_selected: [],
            categoryData: [],
            levelData: [],
            difficultyData: [],
            bookData: [],
        }
    },
    watch: {
    },
    mounted() {
        if (this.userId) {
            this.search.userId = this.userId
        }
        this.getAllCategory()
        this.getAllLevel()
        this.getAllDifficulty()
        this.getAllBook()
    },
    methods: {
        getAllCategory() {
            this.$API.course.category.all.get().then(res => {
                this.categoryData = res.data
            })
        },
        getAllLevel() {
            this.$API.course.level.all.get().then(res => {
                this.levelData = res.data
            })
        },
        getAllDifficulty() {
            this.$API.course.difficulty.all.get().then(res => {
                this.difficultyData = res.data
            })
        },
        getAllBook() {
            this.$API.course.book.all.get().then(res => {
                this.bookData = res.data
            })
        },
        //数据变化
        changedData(res, tableData) {
            if (this.selected && this.selected.length) {
                this.$nextTick(() => {
                    this.selected.forEach(item => {
                        tableData.forEach(itm => {
                            if (item.course.id === itm.course.id) {
                                item.id = itm.id
                                item.course = itm.course
                                item.knowWords = itm.knowWords
                                item.status = itm.status
                                this.$refs.table_member_all.toggleRowSelection(itm, true)
                            }
                        })
                    })
                })
            }
        },
        //确定是否修改已选择的
        handleChange() {
            if (this.temporary_selected.length != this.selected.length) {
                this.selected = this.temporary_selected
                this.selected_visible = false
                this.tableReload()
            } else {
                this.selected_visible = false
            }
        },
        //移除已选择的（多选）
        deleteSelectedMembers() {
            if (this.temporary_selected.length === this.selectedMembers.length) {
                this.temporary_selected = []
                this.selectedMembers = []
            } else {
                this.temporary_selected = this.temporary_selected.filter((item) => {
                    let haveIndex = this.selectedMembers.findIndex(itm => { return itm.course.id === item.course.id })
                    if (haveIndex == -1) {
                        return item
                    }
                })
                this.selectedMembers = []
            }
        },
        //移除已选择的成员
        table_delete(row, index) {
            this.temporary_selected.splice(index, 1)
        },
        //打开已选择的列表查看
        openSelection() {
            this.temporary_selected = JSON.parse(JSON.stringify(this.selected))
            this.selected_visible = true
        },
        //选择已选择的成员
        selectionMembers(e) {
            this.selectedMembers = e
        },
        open(arr) {
            if (arr && arr.length) this.selected = arr
            this.visible = true
        },
        // 重载列表
        tableReload(){
            var params = {}
            for(let i in this.merberSearch){
                if(i == 'id'){
                    params[this.merberSearch[i]] = this.checkTreeID
                }
            }
            let obj = Object.assign(this.defaultSearch, params)
            this.$refs.table_member_all.reload(obj)
        },
        // 确认选择
        async submitAdd() {
            if (this.selected.length > 1) {
                this.$message.error('最多只能选择一个课程')
                return false
            }
            let members = this.selected
            this.$refs.table_member_all.clearSelection()
            this.selected = []
            this.visible = false
            this.$emit('submit', members)
        },
        selectionAll(e) {
            if (e.length) {
                this.selected = unique(this.selected.concat(e))
            } else {
                let nowDataIds = this.$refs.table_member_all.tableData
                nowDataIds.forEach(item => {
                    this.selected.forEach((itm, idx) => {
                        if (item.course.id === itm.course.id) {
                            this.selected.splice(idx, 1)
                        }
                    })
                })
            }
        },

        // 选中一行的时候
        selectionRow(selection, row) {
            const tableData = this.$refs.table_member_all.tableData
            tableData.forEach(ele => {
                if (ele.course.id !== row.course.id) {
                    this.$refs.table_member_all.toggleRowSelection(ele, false)
                }
            })

            this.selectionChange([row])
        },

        /**
         * 选项发生变化
         */
         selectionChange(selections) {
            const tableData = this.$refs.table_member_all.tableData
            //查找未选中的
            let notSelected = []
            tableData.forEach(item => {
               //判断当前页是否包含指定的数据
                let _index = selections.findIndex(_item => { return item.course.id == _item.id })
                let _hasIndex = this.selected.findIndex(_item => { return item.id == _item.id})

                if (_index === -1 && _hasIndex > -1) {
                    notSelected.push(item.id)
                }
            })

            //移除未选中的
            notSelected.forEach(paperId => {
                let index = -1
                this.selected.findIndex((_item, _index) => {
                    if (paperId == _item.id) {
                        index = _index
                        return true
                    }
                    return false
                })

                if (index > -1) {
                    this.selected.splice(index, 1)
                }
            })

            selections.forEach(paper => {
                let index = this.selected.findIndex(item => { return paper.id == item.course.id })
                if (index === -1) {
                    this.selected.push(paper)
                }
            })
        },
        // 关闭显示选择成员弹框
        close() {
            this.visible = false
        },
        // 搜索
        upsearch() {
            this.$refs.table_member_all.upData(this.search)
        },
    }
}
</script>

<style>
</style>